package persistencia;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import model.Veiculo;

public class PersistenciaVeiculo {

	public Veiculo getVeiculo(String chassi){ 
		Connection con = Conexao.getConection();
		Veiculo veiculo = null;
		PreparedStatement ps;
		try {
			String query = "select * from veiculos where chassi = ?";
			ps = con.prepareStatement(query);
			ps.setString(1, chassi);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				veiculo = new Veiculo();
				veiculo.setMarca(rs.getString(2));
				veiculo.setModelo(rs.getString(3));
				veiculo.setPlaca(rs.getString(4));
				veiculo.setChassi(rs.getString(5));
				veiculo.setAno(rs.getString(6));
				veiculo.setCor(rs.getString(7));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return veiculo;
	}
	public ArrayList<Veiculo> getVeiculos(Veiculo veiculo){
		PreparedStatement ps;
		Connection con = Conexao.getConection();
		ArrayList<Veiculo> veiculos = new ArrayList<Veiculo>();
		try {
			String query = "select * from veiculos where chassi = ?";
			ps = con.prepareStatement(query);
			ps.setString(1, veiculo.getChassi());
			ResultSet rs = ps.executeQuery();
			Veiculo veiculoLocal; 
			while (rs.next()) {
				veiculoLocal = new Veiculo();
				veiculoLocal.setMarca(rs.getString(2));
				veiculoLocal.setModelo(rs.getString(3));
				veiculoLocal.setPlaca(rs.getString(4));
				veiculoLocal.setChassi(rs.getString(5));
				veiculoLocal.setAno(rs.getString(6));
				veiculoLocal.setCor(rs.getString(7));
				veiculos.add(veiculoLocal);
				veiculoLocal = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return veiculos;
	}
	public static void inserirVeiculo(Veiculo veiculo) {
		Connection con = Conexao.getConection();
		PreparedStatement ps;
		try {
			String query = "insert into " +
					"veiculos (marca, modelo, placa, chassi, ano, cor) " +
					"values (?,?,?,?,?,?)";
			ps = con.prepareStatement(query);
			ps.setString(1, veiculo.getMarca());
			ps.setString(2, veiculo.getModelo());
			ps.setString(3, veiculo.getPlaca());
			ps.setString(4, veiculo.getChassi());
			ps.setString(5, veiculo.getAno());
			ps.setString(6, veiculo.getCor());
			int status = ps.executeUpdate();
			System.out.println(status);
		}catch(SQLException e){
			e.printStackTrace();
		}
		
	}
}